package com.ssb.plugins;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.ssb.service.check.CheckedFrontSysService;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 产品信息及详情查询
 */
public class ProductInfoDetailPluginImpl implements CustomMethodPlugin {
    private Logger log = Logger.getLogger(getClass());

    @Override
    public Object beforeInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {

        String is_asc = StrUtil.doNull(String.valueOf(map.get("isCreateAsc")), "T");//是否按时间正序=T(默认),倒序=F
        if(map.containsKey("resultObjType")){
            String resultObjType = String.valueOf(map.get("resultObjType"));
            if("obj".equals(resultObjType)&&map.containsKey("ssInsurPro.w_infoId")){
                String proId = String.valueOf(map.get("ssInsurPro.w_infoId"));
                log.info("针对详情查询返回的结果集，补充本产品["+proId+"]对应的明细数组..");

                boolean createTimeIsAsc = ("T".equals(is_asc)?true:false);//按创建时间正序
                //查询该产品配置的：范围，期限，保障内容
                List<DataMap> range_list = getDataList(proId, "ssInsurProRange",createTimeIsAsc);
                List<DataMap> limit_list = getDataList(proId, "ssInsurProLimit",createTimeIsAsc);
                List<DataMap> detail_list = getDataList(proId, "ssInsurProDetail",createTimeIsAsc);

                //按fatherId给子list分组
                Map<String,List> limitMap = getMapByFatherId(limit_list,"rangeId");
                Map<String,List> detailMap = getMapByFatherId(detail_list,"limitId");


                if(limit_list.size()>0){
                    for (DataMap ds : limit_list){
                        List detialArray = new ArrayList();
                        String rangeId = String.valueOf(ds.get("limitId"));
                        if(detailMap.containsKey(rangeId)) {
                            detialArray = detailMap.get(rangeId);
                        }
                        ds.put("detail_array",detialArray);
                    }
                }
                if(range_list.size()>0){
                    for (DataMap ds : range_list){
                        List limitArray = new ArrayList();
                        String rangeId = String.valueOf(ds.get("rangeId"));
                        if(limitMap.containsKey(rangeId)) {
                            limitArray = limitMap.get(rangeId);
                        }
                        ds.put("limit_array",limitArray);
                    }
                }

                DataMap rdm = (DataMap)map.get("resultEntity");
                rdm.put("range_array",range_list);

            }else if("list".equals(resultObjType)){
                Object restObj = map.get("resultEntity");
                List<DataMap> proList = new ArrayList<>();
                if(restObj instanceof Page){
                    Page page = (Page)restObj;
                    proList = page.getPageObjects();
                }else{
                    proList = (List<DataMap>)restObj;
                }

                if(proList.size()>0){
                    log.info("针对列表查询返回的结果集，补充每个产品对应的起始价（范围配的最小保费）..");

                    Map<String,String> pamap = new HashMap<>();
                    Map<String,DataMap> limit_pro_map = getFristLimitGroupByProId(pamap);

                    for (DataMap pro : proList){
                        Map proObj = (Map)pro.get("ssInsurPro");
                        String proId = String.valueOf(proObj.get("infoId"));
                        String minPremium = "";
                        if(limit_pro_map.containsKey(proId)){
                            DataMap fristLimitObj = limit_pro_map.get(proId);
                            minPremium = String.valueOf(fristLimitObj.get("minPremium"));
                        }
                        proObj.put("minPremium",minPremium);
                    }
                }

            }
        }
        return null;
    }

    //查询
    private List getDataList(String proId,String objName,boolean isAsc){
        List<DataMap> dataList = new ArrayList<>();
        Map<String,Object> wMap = new HashMap<>();
        wMap.put(objName+".w_proId", proId);
        if(isAsc){
            wMap.put("orderBy", objName+".create_time asc");
        }else{
            wMap.put("orderBy", objName+".create_time desc");
        }
        ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("list", "s_"+objName, wMap);
        if(resultEntity1!=null && resultEntity1.getEntity()!=null){
            dataList = (List)resultEntity1.getEntity();
        }
        log.info("查询["+objName+"]共计["+dataList.size()+"条]->"+JSONArray.fromObject(dataList));
        return dataList;
    }
    //按fatherId分组
    private Map getMapByFatherId(List<DataMap> dataList,String fatherIdName){
        Map<String,List> resMap = new HashMap<String,List>();
        if(dataList.size()>0){
            for (DataMap ds : dataList){
                List arrayList = new ArrayList();
                String fId = String.valueOf(ds.get(fatherIdName));
                if(resMap.containsKey(fId)) {
                    arrayList = (List) resMap.get(fId);
                }
                arrayList.add(ds);
                resMap.put(fId, arrayList);
            }
        }
        return resMap;
    }

    //获取产品第一个范围数据。
    //按期限表的proId分组取premium最小的值。
    private Map getFristLimitGroupByProId(Map<String,String> parm){
        List<DataMap> dataList = new ArrayList<>();

        StringBuffer sbs = new StringBuffer();
//        sbs.append("select * from ss_insur_pro_limit a,");
//        sbs.append(" (select pro_id,min(premium) min_premium from ss_insur_pro_limit GROUP BY pro_id ) b ");
//        sbs.append(" where a.pro_id = b.pro_id and a.min_premium = b.min_premium order by a.pro_id");

        sbs.append("select pro_id,min(convert(premium,signed)) min_premium from ss_insur_pro_limit GROUP BY pro_id");

        dataList = (List<DataMap>)IusPluginUtil.getInstance().select(sbs.toString(), 0, 0);
        log.info("查询共计["+dataList.size()+"条]->"+JSONArray.fromObject(dataList));

        Map<String,DataMap> resMap = new HashMap<String,DataMap>();
        if(dataList.size()>0){
            for (DataMap ds : dataList){
                List arrayList = new ArrayList();
                String proId = String.valueOf(ds.get("proId"));
                if(!resMap.containsKey(proId)) {
                    resMap.put(proId, ds);
                }
            }
        }
        return resMap;
    }
}
